package com.xcc.shopanim.newa;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager;
import com.nineoldandroids.view.ViewHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xcc.shopanim.AppConstant;
import com.xcc.shopanim.BaseFragment;
import com.xcc.shopanim.MiniLivePhotoFragment;
import com.xcc.shopanim.R;
import com.xcc.shopanim.adapter.ViewPagerAdapter;
import com.xcc.shopanim.mode.BannerMode;
import com.xcc.shopanim.mode.ImageMode;
import com.xcc.shopanim.mode.MainLiveVideoGroupMode;
import com.xcc.shopanim.mode.NewMainVideoMode;
import com.xcc.shopanim.widget.RatioFrameLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainLiveFragment extends BaseFragment implements OnRefreshListener, LayoutDrawerViewHolder.OnLayoutDrawerListener {
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;
    @BindView(R.id.horizontalViewPager)
    HorizontalInfiniteCycleViewPager horizontalViewPager;
    @BindView(R.id.layoutContent)
    View layoutContent;
    @BindView(R.id.layoutRatio)
    RatioFrameLayout layoutRatio;
    @BindView(R.id.layoutDrawer)
    ViewGroup layoutDrawer;
    @BindView(R.id.imgLive)
    ImageView imgLive;
    @BindView(R.id.textMakeAnLive)
    TextView textMakeAnLive;
    private LayoutDrawerViewHolder drawerViewHolder;
    private List<NewMainVideoMode> modeList;
    private List<BaseFragment> fragmentList;
    private ViewPagerAdapter pagerAdapter;
    private int ratioHeight;//原始的高度

    public static MainLiveFragment newInstance() {
        MainLiveFragment fragment = new MainLiveFragment();
        return fragment;
    }

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.newa_fragment_main_live, null);
        ButterKnife.bind(this, view);
        Resources res = getResources();
        final int qb_px_20 = -(int) res.getDimension(R.dimen.qb_px_20);
        final int qb_px_25 = -(int) res.getDimension(R.dimen.qb_px_25);
        ViewGroup.LayoutParams layoutParams = layoutRatio.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) layoutParams;
            params.topMargin = qb_px_25;
            params.bottomMargin = qb_px_20;
            layoutRatio.setLayoutParams(params);
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        modeList = new ArrayList<>();
        fragmentList = new ArrayList<>();
        pagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), fragmentList);
        horizontalViewPager.setAdapter(pagerAdapter);
        horizontalViewPager.setOffscreenPageLimit(5);
        horizontalViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (drawerViewHolder == null) return;
                drawerViewHolder.onPageSelected(position);
            }
        });

        smartLayout.setOnRefreshListener(this);
        smartLayout.setEnableLoadMore(false);

        isInit = true;
        stateChange();
        drawerViewHolder = new LayoutDrawerViewHolder(getActivity(), layoutDrawer, modeList)
                .setOnLayoutDrawerListener(this);
        layoutDrawer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                layoutDrawer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                setH();
            }

            private void setH() {
                int height = layoutContent.getHeight();
                if (height > 0) {
                    ViewGroup.LayoutParams layoutParams = layoutDrawer.getLayoutParams();
                    if (layoutParams != null) {
                        layoutParams.height = height;
                        layoutDrawer.setLayoutParams(layoutParams);
                    }
                    layoutParams = layoutContent.getLayoutParams();
                    if (layoutParams != null) {
                        layoutParams.height = height;
                        layoutContent.setLayoutParams(layoutParams);
                    }
                    drawerViewHolder.initRecyclerView();
                    ratioHeight = layoutRatio.getHeight();
                } else layoutDrawer.postDelayed(this::setH, 50);
            }
        });
        Glide.with(getActivity()).asGif()
                .load(R.raw.img_main_side_livegif_)
                .into(imgLive);
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        stateChange();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        stateChange();
    }

    @Override
    public void onResume() {
        super.onResume();
        stateChange();
    }

    @Override
    public void onPause() {
        super.onPause();
        stateChange();
    }

    private void stateChange() {
        boolean isShow;
        if (isPause || hidden) {
            isShow = false;
        } else {
            isShow = isVisibleToUser && isInit;
        }
        if (isShow) {
            if (isViewResume)
                return;
            viewResume();
        } else {
            if (isViewResume)
                viewPause();
        }
    }

    private boolean isViewResume;
    private boolean isVisibleToUser;
    private boolean isInit;

    private void viewResume() {
        isViewResume = true;
        if (modeList.size() == 0) smartLayout.autoRefresh();
        if (fragmentList.size() > 0) {
            int currentItem = horizontalViewPager.getCurrentItem();
            BaseFragment fragment = fragmentList.get(currentItem);
            fragment.onHiddenChanged(false);
        }
    }

    private void viewPause() {
        isViewResume = false;
        if (fragmentList.size() > 0) {
            int currentItem = horizontalViewPager.getCurrentItem();
            BaseFragment fragment = fragmentList.get(currentItem);
            fragment.onHiddenChanged(true);
        }
    }

    @Override
    public void sendMessage(int type, Object object) {
        if (type == 0xF0011) drawerViewHolder.changeOpen();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        MainLiveVideoGroupMode videoGroupMode = new MainLiveVideoGroupMode();
        List<NewMainVideoMode> videoModeList = videoGroupMode.getVideoModeList();
        String[] urls = {AppConstant.ImgDebugUrl,
                AppConstant.ImgDebugUrl2,
                AppConstant.ImgDebugUrl3,
                AppConstant.ImgDebugUrl4,
                AppConstant.ImgDebugUrl5,
                AppConstant.ImgDebugUrl6,
                AppConstant.ImgDebugUrl7,
                AppConstant.ImgDebugUrl8,
                AppConstant.ImgDebugUrl9,
                AppConstant.ImgDebugUrl10};
        for (int i = 0; i < urls.length; i++) {
            BannerMode bannerMode = new BannerMode();
            bannerMode.pictureKey = new ImageMode(urls[i]);
            videoModeList.add(new NewMainVideoMode("rookiCi" + i, -3).setBannerMode(bannerMode));
        }
        smartLayout.postDelayed(() -> getVideoListRet(videoGroupMode, true), 100);
    }

    public void getVideoListRet(MainLiveVideoGroupMode groupMode, boolean isClear) {
        if (groupMode == null) groupMode = new MainLiveVideoGroupMode();
        List<NewMainVideoMode> list = groupMode.getVideoModeList();
        smartLayout.finishRefresh(50);
        if (!isClear) return;
        //if (isClear) {
        modeList.clear();
        fragmentList.clear();
        horizontalViewPager.removeAllViewsInLayout();
        //}
        for (int i = 0; i < list.size(); i++) {
            NewMainVideoMode videoMode = list.get(i);
            if (hasVideo(videoMode)) {
                continue;
            }
            modeList.add(videoMode);
            BaseFragment fragment = getFragment(videoMode);
            fragmentList.add(fragment);
        }
        pagerAdapter.notifyDataSetChanged();
        drawerViewHolder.notifyDataSetChanged();
    }

    private boolean hasVideo(NewMainVideoMode videoMode) {
        if (videoMode == null) return true;
        for (int i = 0; i < modeList.size(); i++) {
            NewMainVideoMode mode = modeList.get(i);
            if (videoMode.equals(mode)) {
                return true;
            }
        }
        return false;
    }

    private BaseFragment getFragment(NewMainVideoMode videoMode) {
        BaseFragment fragment;
        /*if (videoMode.contentType == 5 || videoMode.contentType == -2) {
            fragment = MiniLiveNoticeFragment.newInstance(videoMode);
        } else if (videoMode.contentType == 1) {
            fragment = MiniLiveRoomFragment.newInstance(videoMode);
        } else if (videoMode.contentType == 4 || videoMode.contentType == -1) {
            fragment = MiniLiveBackPlayFragment.newInstance(videoMode);
        } else {}*/
        fragment = MiniLivePhotoFragment.newInstance(videoMode);

        return fragment;
    }

    @Override
    public void onChangeOpen(boolean open) {
        if (onFragmentCallBack == null) return;
        onFragmentCallBack.onFragmentCallBack(this, 7, open);
    }

    @Override
    public void onLayoutDrawerClick(NewMainVideoMode mode) {
        int position = modeList.indexOf(mode);
        if (position < 0) return;
        int currentItem = horizontalViewPager.getCurrentItem();
        if (position == currentItem) return;
        horizontalViewPager.setCurrentItem(position);
    }

    @Override
    public void onContentOffset(float offset) {
        if (offset == 0) {
            ViewHelper.setScaleX(layoutRatio, 1);
            ViewHelper.setScaleY(layoutRatio, 1);
            ViewHelper.setTranslationY(layoutRatio, 0);
        } else {
            float h = ratioHeight - offset;//目标高度
            ViewHelper.setScaleX(layoutRatio, h / ratioHeight);
            ViewHelper.setScaleY(layoutRatio, h / ratioHeight);
            ViewHelper.setTranslationY(layoutRatio, -offset / 2);
        }
    }
}
